<?php
namespace Api\Controller;
use Shop\Api\CategoryApi;
use Shop\Api\ProductApi;
use Shop\Api\ProductSkuApi;
use Shop\Api\ShoppingCartApi;

/**
 * Created by PhpStorm.
 * User: an
 * Date: 2015/8/21
 * Time: 8:51
 */

class ShoppingCartController extends ApiController{



    /**
     * 添加到购物车
     * 如果购物车里已有，则修改数量
     */
    public function add(){
        
        $notes = "应用" . $this->client_id . "，调用购物车添加接口";
        addLog("ShoppingCart/add", $_GET, $_POST, $notes);
        $uid= $this->_post("uid");

        $id = $this->_post("p_id",0,'缺失商品ID');//缺失商品ID
        $count = $this->_post("count",1);//默认一件
        $psku_id = $this->_post("psku_id",'');//默认一件
        $sku_desc = $this->_post("sku_desc",'');//默认一件
        if($id < 0){
            $this->error("商品ID缺失！");
        }
        if($count <= 0){
            $this->error("商品数量不对！");
        }

        $result = apiCall(ProductApi::DETAIL, array($id));

        if(!$result['status']){
            LogRecord($result['info'], __FILE__.__LINE__);
            $this->error($result['info']);
        }

        if(is_null($result['info'])){
            $this->error("商品信息获取失败！");
        }

        $product = $result['info'];

        $result = apiCall(ProductSkuApi::GET_INFO, array(array('id'=>$psku_id)));

        if(!$result['status']){
            $this->error($result['info']);
        }

        $sku = $result['info'];


        if($product['has_sku'] == 1 && empty($psku_id)){
            $this->error("请先选择规格!");
        }

        $result = false;
        if($product['has_sku'] == 0){

            $result = $this->addToCart($uid,$product,false,$count);

        }elseif($product['has_sku'] == 1 && is_array($sku)){

            if(is_null($sku)){
                $this->error("商品规格信息获取失败！");
            }

            $sku['sku_desc'] = $sku_desc;
            //多规格
            $result = $this->addToCart($uid,$product,$sku,$count);

        }else{
            $this->error("操作失败！");
        }

        if(is_array($result) && $result['status']){
            $cart_id = $result['info'];

            $this->apiReturnSuc($cart_id);

        }else{
            $msg = $result['info'];
            if(empty($msg)){
                $msg = "添加失败！";
            }
            $this->apiReturnErr($msg);
        }


    }

    /**
     * 删除购物车
     *
     */
    public function delete(){
        $notes = "应用" . $this->client_id . "，调用购物车删除接口";
        addLog("ShoppingCart/delete", $_GET, $_POST, $notes);
        $id=I('id',0);//获取购物车ID
        $map=array(
            'id'=>$id,
        );
        $result= apiCall(ShoppingCartApi::DELETE,array($map));
        if($result['status']){
            $this->apiReturnSuc($result['info']);
        }else{
            $this->apiReturnErr("删除失败");
        }
    }


    /**
     * 更新购物车
     *
     */
    public function update(){
        $notes = "应用" . $this->client_id . "，调用购物车修改接口";
        addLog("ShoppingCart/update", $_GET, $_POST, $notes);
        $id=$this->_post("id",0);//获取购物车ID
        $count= $this->_post("count",0); //数量
        $express=$this->_post("express",0);//运费
        $psku_id=$this->_post("psku_id",0); //规格id
        $p_id=$this->_post("p_id",0);
        if($count==0){
            $this->apiReturnErr("数量必须大于1");
        }

        //如果没规格，判断为商品的库存,如果有，按规格库存来
        if( $psku_id==0){
            $map=array(
                'id'=>$p_id
            );
            $result=apiCall(ProductApi::GET_INFO,array($map));
        }else{
            $map=array(
                'id'=>$psku_id
            );
            $result=apiCall(ProductSkuApi::GET_INFO,array($map));
        }
        if($result['status']){
            if($result['info']['quantity']<$count){
                $this->apiReturnErr("超出商品库存");
            }
        }else{
            $this->apiReturnErr("发生异常，稍候再试");
        }
        $map=array(
            'count'=>$count,
            'express'=>$express,
        );
        $result=apiCall(ShoppingCartApi::SAVE_BY_ID,array($id,$map));
        if($result['status']){
            $this->apiReturnSuc($result['info']);
        }else{
            $this->apiReturnErr("修改失败");
        }
    }

    /**
     * 查询购物车
     */
    public function query(){
        $notes = "应用" . $this->client_id . "，调用购物车分页查询接口";
        addLog("ShoppingCart/query", $_GET, $_POST, $notes);

        //获取用户ID
        $uid=I('uid',0);

        $map=array(
          'uid'=>  $uid
        );

        $page = array('curpage'=>I('pageNo',0),'size'=>I('pageSize',20)); //分页查询
        $order="store_id desc,update_time desc";
        $result=apiCall(ShoppingCartApi::QUERY,array($map,$page,$order));

        if($result['status']){
            $list = $result['info']['list'];
            if(is_array($list)){
                foreach($list as &$vo){
                    $vo['icon_url'] = getImageUrl($vo['icon_url']);
                }
            }

            $this->apiReturnSuc($list);
        }else{
            $this->apiReturnErr("您的购物车暂时为空");
        }
    }


    /**
     * 查询单个购物车
     */
    public function getInfo(){
        $notes = "应用" . $this->client_id . "，调用单个购物车查询接口";
        addLog("ShoppingCart/getInfo", $_GET, $_POST, $notes);
        //获取用户ID
        $id=I('id',0);
        $map=array(
            'id'=>  $id
        );
        $result=apiCall(ShoppingCartApi::GET_INFO,array($map));
        if($result['status']){
            if($result['info']!=null){
                $this->apiReturnSuc($result['info']);
            }else{
                $this->apiReturnErr("查询失败");
            }

        }else{
            $this->apiReturnErr("查询失败");
        }
    }





    /**
     * 购物车对应商品库存
     * 如果购物车里已有，则修改数量
     */
    public function count(){
        $notes = "应用" . $this->client_id . "，调用购物车对应商品库存接口";
        addLog("ShoppingCart/count", $_GET, $_POST, $notes);
        $p_id= $this->_post("p_id",0);
        $psku_id=$this->_post("psku_id",0);

        if(empty($p_id)){
            $this->apiReturnErr("缺少参数p_id=".$p_id.";psku_id=".$psku_id);
            renturn;
        }


       if($psku_id==0){
          $map=array(
              'id'=>$p_id
          );
          $result=apiCall(ProductApi::GET_INFO,array($map));
       }else{
           $map=array(
               'id'=>$psku_id
            );
           $result=apiCall(ProductSkuApi::GET_INFO,array($map));
        }
        if($result['status']){
            $pcount=(int)$result['info']['quantity'];
            $this->apiReturnSuc($pcount);
        }else{
            $this->apiReturnErr("发生异常，请稍候再试");
        }
    }




    /**
     * 添加到购物车
     * 如果购物车里已有，则修改数量
     */
    public function addArray(){
        $notes = "应用" . $this->client_id . "，调用购物车数组添加接口";
        addLog("ShoppingCart/addArray", $_GET, $_POST, $notes);
        $uid= $this->_post("uid");
        $store_id= $this->_post("store_id");
        $p_id= $this->_post("p_id");
        $sku_id= $this->_post("sku_id",-1);
        $sku_desc= $this->_post("sku_desc",-1);
        $icon_url= $this->_post("icon_url",-1);
        $count= $this->_post("count",-1);
        $name= $this->_post("name",-1);
        $express=$this->_post("express",-1);
        $price=$this->_post("price",-1);
        $ori_price=$this->_post("ori_price",-1);
        $psku_id=$this->_post("psku_id",-1);
        $weight=$this->_post("weight",-1);
        $taxrate=$this->_post("taxrate",-1);
        if(empty($uid)){
            $this->apiReturnErr("缺少参数uid");
            renturn;
        }

        $this->isError($sku_id,"sku_id");
        $this->isError($sku_desc,"sku_desc");
        $this->isError($icon_url,"icon_url");
        $this->isError($count,"count");
        $this->isError($name,"name");
        $this->isError($express,"express");
        $this->isError($price,"price");
        $this->isError($ori_price,"ori_price");
        $this->isError($psku_id,"psku_id");
        $this->isError($weight,"weight");
        $this->isError($taxrate,"taxrate");
        $counts="";
        foreach($count as $c){
            $counts.=$c.";";
        }
        $error=0;
        for($i=0;$i<count($store_id);$i++) {
            if (empty($store_id[$i]) || empty($p_id[$i])) {
                $this->apiReturnErr("有缺少的参数store_id:" . $store_id . "pid:" . $p_id);
                renturn;
            }
            $this->toAdd($uid,$store_id[$i], $p_id[$i], $sku_id[$i], $sku_desc[$i], $icon_url[$i], $count[$i], $name[$i], $express[$i], $price[$i], $ori_price[$i], $psku_id[$i],$weight[$i],$taxrate[$i]);
        }
        if($error==0){
            $this->apiReturnSuc("添加成功".$counts);
        }
    }


    /**
     * 商品id，商品名称，商品图片（默认主图），商品数量count，是否多规格，商品价格，商品原价，
     * 运费,
     * @param $uid
     * @param $product
     * @param $sku
     * @param $count
     * @return array|mixed
     */
    private function addToCart($uid,$product,$sku,$count){

        $result = apiCall(CategoryApi::GET_INFO,array(array('code'=>$product['dt_tariff_code'])));
        $taxRate = 0;
        if($result['status'] && is_array($result['info'])){
            $taxRate = $result['info']['taxrate'];
        }
        $item = array(
            'uid'=>$uid,
            'p_id'=>$product['id'],
            'icon_url'=>$product['main_img'],//商品图片
            'count'=>$count, // 商品数量
            'name'=>$product['name'],
            'has_sku'=>$product['has_sku'],
            'sku_desc'=>'',
            'sku_id'=>'',
            'store_id'=>$product['store_id'],
            'express'=>0,
            'weight'=>$product['weight'],
            'taxrate'=>$taxRate,
            'template_id'=>$product['template_id'],
        );

        if($sku === false){
            //统一规格下
            $item['price'] = $product['price'];
            $item['ori_price'] = $product['ori_price'];
        }else{
            $item['sku_id'] = $sku['sku_id'];
            $item['psku_id'] = $sku['id'];
            $item['price'] = $sku['price'];
            $item['ori_price'] = $sku['ori_price'];
            $item['sku_desc'] = $sku['sku_desc'];
            if(!empty($sku['icon_url'])){
                $item['icon_url'] = $sku['icon_url'];//商品图片
            }
        }

        if($item['p_id'] <= 0 || empty($item['p_id'])){
            $this->error("商品ID有问题! ");
        }

        addLog("ShoppingCart/addToCart",$map,$item,"[调试]");
        $map = array(
            'uid'=>$uid,
            'p_id'=>$item['p_id'],
        );

        if($sku){
            $map['psku_id'] = $item['psku_id'];
        }
        $result = apiCall(ShoppingCartApi::GET_INFO,array($map));
        addLog("ShoppingCart/addToCart",$map,$result,"[调试]");

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
            return array('status'=>false,'info'=>"参数错误!");
        }
        $cart_id = 0;
        $error = "";
        if(is_array($result['info'])){
            $entity = array(
                'count'=>($result['info']['count'] + $item['count']),
                'name'=>$product['name'],
                'icon_url'=>$product['main_img'],//商品图片
            );
            $cart_id = $result['info']['id'];
            $result = apiCall(ShoppingCartApi::SAVE_BY_ID,array($cart_id,$entity));
            if(!$result['status']){
                $error = $result['info'];
            }
        }else{

            $result = apiCall(ShoppingCartApi::ADD,array($item));
            addLog("ShoppingCartApi/ADD", $item, $result, "item值");
            if($result['status']){
                $cart_id = $result['info'];
            }else{
                $error = $result['info'];
            }


        }

        $this->checkApiCallResult($result);
        $cart_id = intval($cart_id);
        if($cart_id > 0){
            return array('status'=>true,'info'=>$cart_id);
        }else{
            return array('status'=>false,'info'=>$error);;
        }
    }


    function isError($info,$name){
        if($info==-1){
            $this->apiReturnErr("缺少参数".$name);
        }
    }

    function getSupportMethod(){

    }
}